1. 20.7 lightGBM案例介绍

1.1. 学习目标

  • 通过鸢尾花数据集知道lightGBM算法对应api的使用

接下来,通过鸢尾花数据集对lightGBM的基本使用,做一个介绍。

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import mean_squared_error
import lightgbm as lgb

加载数据,对数据进行基本处理

# 加载数据
iris = load_iris()
data = iris.data
target = iris.target
X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2)

模型训练

gbm = lgb.LGBMRegressor(objective='regression', learning_rate=0.05, n_estimators=20)

gbm.fit(X_train, y_train, eval_set=[(X_test, y_test)], eval_metric='l1', early_stopping_rounds=5)

gbm.score(X_test, y_test)
# 0.810605595102488

image-20230712102651995

#  网格搜索,参数优化
estimator = lgb.LGBMRegressor(num_leaves=31)
param_grid = {
    'learning_rate': [0.01, 0.1, 1],
    'n_estimators': [20, 40]
}
gbm = GridSearchCV(estimator, param_grid, cv=4)
gbm.fit(X_train, y_train)
print('Best parameters found by grid search are:', gbm.best_params_)
# Best parameters found by grid search are: {'learning_rate': 0.1, 'n_estimators': 40}

模型调优训练

gbm = lgb.LGBMRegressor(num_leaves=31, learning_rate=0.1, n_estimators=40)

gbm.fit(X_train, y_train, eval_set=[(X_test, y_test)], eval_metric='l1', early_stopping_rounds=5)

gbm.score(X_test, y_test)
# 0.9536626296481988
Copyright © MISIN 2022 | 豫ICP备2023040351号-1 all right reserved,powered by Gitbook该文件修订时间: 2024-01-12 07:58:59

results matching ""

    No results matching ""